package avortep.synchro;

import java.sql.ResultSet;
import java.sql.SQLException;

import avortep.model.DBColumn;
import avortep.model.DBTable;
import avortep.model.DBView;
import avortep.model.type.DBType;

public class DBSqlReader {
	
	protected String sqlGetTables;
	protected String sqlGetColumns;	
	protected String sqlGetViews;
	protected String schemaName;
	protected String tableName="TABLE_NAME";
	protected String columnName="COLUMN_NAME";
	protected String typeName="TYPE_NAME";
	protected String viewSourceName="VIEW_SOURCE";
	protected String defaultSource="COLUMN_DEFAULT";
	protected String isNullable="IS_NULLABLE";
	protected String checkClause="CHECK_CLAUSE";
	
	protected DBSqlReader() {
		// TODO Auto-generated constructor stub
	}

	protected DBTable getTable(ResultSet data) throws SQLException {
		DBTable table = new DBTable(data.getString(tableName));
		if (schemaName!=null)
			table.setSchema(data.getString(schemaName));		
		return table;
	}

	protected DBColumn getColumn(ResultSet data) throws SQLException {
		DBColumn column = new DBColumn(data.getString(columnName), new DBType(data.getString(typeName)));
		column.setDefaultValue(getDefaultValue(data));
		column.setIsNullable(getIsNullable(data));
		column.setCheckClause(getCheck(data));
		if (schemaName!=null)
			column.setSchema(data.getString(schemaName));			
		return column;
	}

	protected String getCheck(ResultSet data) throws SQLException {
		return data.getString(checkClause);		
	}

	protected boolean getIsNullable(ResultSet data) throws SQLException {
		return (data.getString(isNullable) == null);	
	}

	protected String getDefaultValue(ResultSet data) throws SQLException {
		return data.getString(defaultSource);
	}

	protected DBView getView(ResultSet data) throws SQLException {
		DBView view = new DBView(data.getString(tableName));
		view.setQuery(data.getString(viewSourceName));
		if (schemaName!=null)
			view.setSchema(data.getString(schemaName));		
		return view;
	}

	public String getTableName(ResultSet data) throws SQLException {		
		return data.getString(tableName);
	}

	protected String getSqlGetTables() {
		return sqlGetTables;
	}

	protected String getSqlGetColumns() {
		return sqlGetColumns;
	}

	protected String getSqlGetViews() {
		return sqlGetViews;
	}
	
}
